def path(paths):
    result = paths[0]
    for p in paths[1:]:
        result = os.path.join(result, p)
    return result

import cv2
from PIL import Image
from typing import Dict, Any


class MediaComparator:
    def __init__(self, image_threshold: float = 0.9, video_threshold: float = 0.8):
        """
        初始化媒体比较器

        参数:
            image_threshold: 图片相似度阈值 (0-1)
            video_threshold: 视频相似度阈值 (0-1)
        """
        self.image_threshold = image_threshold
        self.video_threshold = video_threshold

    def compare(self, file1_path: str, file2_path: str) -> Dict[str, Any]:
        """
        比较两个文件系统中的文件

        参数:
            file1_path: 第一个文件的路径
            file2_path: 第二个文件的路径

        返回:
            包含比较结果的字典
        """
        # 检查文件是否存在
        for path in [file1_path, file2_path]:
            if not os.path.exists(path):
                return {
                   'match': False,
                   'similarity': 0.0,
                   'reason': f"文件不存在: {path}",
                    'details': {}
                }

        # 获取文件类型
        file1_type = self._get_file_type(file1_path)
        file2_type = self._get_file_type(file2_path)
        print(file1_type, file2_type)

        # 类型不匹配
        if file1_type != file2_type:
            return {
               'match': False,
               'similarity': 0.0,
               'reason': f"文件类型不匹配: 第一个文件为{file1_type}，第二个文件为{file2_type}",
                'details': {}
            }

        # 根据类型进行比较
        if file1_type == 'image':
            return self._compare_images(file1_path, file2_path)
        elif file1_type == 'video':
            return self._compare_videos(file1_path, file2_path)
        else:
            return {
               'match': False,
               'similarity': 0.0,
               'reason': "不支持的文件类型",
                'details': {}
            }

    def _get_file_type(self, path: str) -> str:
        """获取文件类型"""
        ext = os.path.splitext(path)[1].lower()
        print(ext)
        if ext in ('.jpg', '.jpeg', '.png', '.gif', '.bmp'):
            return 'image'
        elif ext in ('.mp4', '.avi', '.mov', '.mkv', '.flv'):
            return 'video'
        else:
            return 'unknown'

    def _compare_images(self, file1_path: str, file2_path: str) -> Dict[str, Any]:
        """比较两张图片"""
        # 1. 文件大小比较
        size_ratio = self._compare_size(file1_path, file2_path)

        # 2. 分辨率比较
        res1 = self._get_image_resolution(file1_path)
        res2 = self._get_image_resolution(file2_path)
        res_similarity = self._compare_resolution(res1, res2)

        # 综合评分
        similarity = (size_ratio * 0.15) + (res_similarity * 0.85)
        match = similarity >= self.image_threshold

        return {
           'match': match,
           'similarity': round(similarity, 3),
           'reason': "" if match else "相似度低于阈值",
            'details': {
               'size_ratio': round(size_ratio, 3),
               'resolution': {
                    'file1': res1,
                    'file2': res2,
                   'similarity': round(res_similarity, 3)
                },
            }
        }

    def _compare_videos(self, file1_path: str, file2_path: str) -> Dict[str, Any]:
        """比较两个视频"""
        # 1. 文件大小比较
        size_ratio = self._compare_size(file1_path, file2_path)

        # 2. 分辨率比较
        res1 = self._get_video_resolution(file1_path)
        res2 = self._get_video_resolution(file2_path)
        res_similarity = self._compare_resolution(res1, res2)

        # 3. 帧率比较
        fps1 = self._get_video_fps(file1_path)
        fps2 = self._get_video_fps(file2_path)
        fps_similarity = min(fps1, fps2) / max(fps1, fps2)

        # 4. 帧数比较
        frames1 = self._get_video_frame_count(file1_path)
        frames2 = self._get_video_frame_count(file2_path)
        frame_similarity = min(frames1, frames2) / max(frames1, frames2)

        # 综合评分
        similarity = (size_ratio * 0.1) + (res_similarity * 0.3) + \
                     (fps_similarity * 0.3) + (frame_similarity * 0.3)
        match = similarity >= self.video_threshold

        return {
           'match': match,
           'similarity': round(similarity, 3),
           'reason': "" if match else "相似度低于阈值",
            'details': {
               'size_ratio': round(size_ratio, 3),
               'resolution': {
                    'file1': res1,
                    'file2': res2,
                   'similarity': round(res_similarity, 3)
                },
                'fps': {
                    'file1': fps1,
                    'file2': fps2,
                   'similarity': round(fps_similarity, 3)
                },
                'frame_count': {
                    'file1': frames1,
                    'file2': frames2,
                   'similarity': round(frame_similarity, 3)
                },
            }
        }

    def _compare_size(self, path1: str, path2: str) -> float:
        """比较文件大小"""
        size1 = os.path.getsize(path1)
        size2 = os.path.getsize(path2)
        return min(size1, size2) / max(size1, size2)

    def _get_image_resolution(self, path: str) -> tuple:
        """获取图片分辨率"""
        img = Image.open(path)
        return img.size

    def _compare_resolution(self, res1: tuple, res2: tuple) -> float:
        """比较分辨率"""
        if res1 == res2:
            return 1.0
        # 计算宽高比差异
        ratio1 = res1[0] / res1[1]
        ratio2 = res2[0] / res2[1]
        ratio_diff = abs(ratio1 - ratio2) / max(ratio1, ratio2)
        return 1.0 - ratio_diff

    def _get_video_resolution(self, path: str) -> tuple:
        """获取视频分辨率"""
        cap = cv2.VideoCapture(path)
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        cap.release()
        return (width, height)

    def _get_video_fps(self, path: str) -> float:
        """获取视频帧率"""
        cap = cv2.VideoCapture(path)
        fps = cap.get(cv2.CAP_PROP_FPS)
        cap.release()
        return fps

    def _get_video_frame_count(self, path: str) -> int:
        """获取视频帧数"""
        cap = cv2.VideoCapture(path)
        count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        cap.release()
        return count

import json
from pathlib import Path
import os

def read_json_file(file_path: str) -> dict:
    """读取JSON文件并返回字典

    Args:
        file_path: JSON文件的路径

    Returns:
        包含JSON数据的字典

    Raises:
        FileNotFoundError: 文件不存在
        json.JSONDecodeError: JSON格式错误
        PermissionError: 没有读取权限
    """
    # 确保文件存在
    path = Path(file_path)
    if not path.exists():
        raise FileNotFoundError(f"文件不存在: {file_path}")

    # 确保是文件而不是目录
    if not path.is_file():
        raise ValueError(f"不是文件: {file_path}")

    # 读取并解析JSON
    with open(path, 'r', encoding='utf-8') as f:
        return json.load(f)

# 使用示例
if __name__ == "__main__":
    mediaComparator = MediaComparator()
    img1 = "./test_pic/1004.jpg"
    img2 = "./processed/127.0.0.1/1004.jpg"
    img3 = "./test_pic/1202.jpg"
    # 图片比较示例
    try:
        result = mediaComparator.compare(img1,img2)
        print(f"图片比较结果: {'相似' if result['match'] else '不相似'}")
        print(result)
    except Exception as e:
        print(f"错误: {e}")
    video1 = "./uploads/127.0.0.1/test1.mp4"
    video2 = "./processed/127.0.0.1/test1.mp4"
    video3 = "./uploads/127.0.0.1/test2.mp4"
    # 视频比较示例
    try:
        result = mediaComparator.compare(video1,video2)
        print(f"视频比较结果: {'相似' if result['match'] else '不相似'}")
        print(result)
    except Exception as e:
        print(f"错误: {e}")